<?php

include 'simplepie.inc';
include 'idn/idna_convert.class.php';
if ($_SERVER['SERVER_NAME'] == 'hathmaluwa.lk') {
    $con = mysql_connect("localhost", "root", "");
    mysql_select_db("hathmaluwa_zend");
} else {
    $con = mysql_connect("mysql.extrosolutions.com", "extroso", "");
    mysql_select_db("extroso_temp_db1");
}
mysql_set_charset('utf8', $con);
date_default_timezone_set('Asia/Colombo');
if (!$con) {
    die('db error');
}

function StupefyEntities($s = '') {
    $inputs = array('â€“', 'â€”', 'â€˜', 'â€™', 'â€œ', 'â€�', 'â€¦', '[', ']');
    $outputs = array('-', '--', "'", "'", '"', '"', '...', '[', ']');
    $s = str_replace($inputs, $outputs, $s);
    return $s;
}

function trunc($phrase, $max_words) {
    $phrase_array = explode(' ', $phrase);
    if (count($phrase_array) > $max_words && $max_words > 0)
        $phrase = implode(' ', array_slice($phrase_array, 0, $max_words));
    return $phrase;
}

$result = mysql_query("SELECT language,feed_url,blog_id FROM blog_info WHERE last_bot_visit <= SUBDATE(now(), interval 1 hour) AND status = 'approved'");
while ($row = mysql_fetch_assoc($result)) {
    try {
        $feed = new SimplePie();
        $feed->set_stupidly_fast(true);
        $feed->set_feed_url($row['feed_url']);
        echo $row['feed_url'] . "\n";
        $feed->set_input_encoding('UTF-8');
        $feed->set_output_encoding('UTF-8');
        $feed->set_useragent('hathmaluwa-bot');
        $feed->enable_cache(false);
        $feed->set_timeout(5);
        $success = $feed->init();
        $feed->handle_content_type();
        if ($feed->error()) {
            echo "\n---------------------------error-------------------\n";
//            mysql_query("UPDATE blog_info SET status='problematic' WHERE blog_id = '" . $row['blog_id'] . "'") or print(mysql_error());
        }

        $a = 0;
        $prevHashs = array();
        $res = mysql_query("SELECT hash FROM blog_post_info WHERE blog_id='" . $row['blog_id'] . "' ORDER BY posted_time DESC LIMIT 4");

        while (($prevHashs[] = mysql_fetch_object($res)->hash) || array_pop($prevHashs)

            );
        mysql_free_result($res);
        $items = $feed->get_items(0, 4);
        foreach ($items as $item) {
            //get current items
            $hash = $item->get_id(true);
            if (!(in_array($hash, $prevHashs))) {
                $short_desc = trunc(addslashes(trim(str_replace("&nbsp;", '', str_replace("\n", ' ', str_replace("\r", ' ', strip_tags(StupefyEntities($item->get_description()))))))), 70);
                $author = $item->get_author();
                mysql_query("INSERT INTO blog_post_info (blog_id,posted_time,blog_post_summery,blog_post_title,blog_post_url,hash,author)
                        VALUES ('" . $row['blog_id'] . ".','" . $item->get_date("Y-m-d H:i:s") . "','$short_desc','" . addslashes($item->get_title(true)) . "','" . $item->get_permalink() . "','" . $hash . "','" . $author . "')") or die(mysql_error());
            } else {
                break 1;
            }
        }
        $feed->__destruct();
        unset($items);
        unset($feed);
        mysql_query("UPDATE blog_info SET last_bot_visit=now() WHERE blog_id=" . $row['blog_id']) or die(mysql_error());
    } catch (Exception $e) {
        echo $e->getMessage();
        echo "blog id " . $row['blog_id'] . "looks problematic " . $row['feed_url'] . "\n";
//        mysql_query("UPDATE blog_info SET status='problematic' WHERE blog_id=".$row['blog_id']);
    }
}

mysql_free_result($result);
mysql_close();
?>
